package com.yyfax.ph.home.recommendlas;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.Loader;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.yyfax.common.CLog;
import com.yyfax.common.tools.DensityUtil;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.ph.R;
import com.yyfax.ph.base.PermissionActivity;
import com.yyfax.ph.common.GlobalVariableConfig;
import com.yyfax.ph.common.imageselector.utils.FileUtils;
import com.yyfax.ph.common.share.ShareAgent;
import com.yyfax.ph.common.utils.QRCodeUtil;
import com.yyfax.ph.common.utils.VibratorUtil;
import com.yyfax.ph.common.widgets.pagerindicator.InkPageIndicator;
import com.yyfax.ph.home.recommendloan.RecommendPermissionModel;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 云贷扫码推荐
 */
public class LASScanRecommendActivity extends PermissionActivity implements View.OnLongClickListener, ShareAgent.MsgSender {
	private static final String TAG = "LASScanRecommendActivity";

	public static final String TITLE = "title";
	public static final String CONTENT = "content";
	public static final String URI = "url";
	public static final String CODE = "code";
	public static final String LEFT_RECOMMEND_LAS_TIMES = "left_recommend_las_times";
	private static final String IMAGE_FILE_NAME = "LASRecommendQrCodeImg" + ".jpg";
	private static final String wxPackage = "com.tencent.mm";

	@BindView(R.id.viewpager)
	ViewPager mViewpager;
	@BindView(R.id.ink_pager_indicator)
	InkPageIndicator mInkPagerIndicator;
	@BindView(R.id.we_chat_friend)
	LinearLayout mWeChatFriend;
	@BindView(R.id.we_chat_circle)
	LinearLayout mWeChatCircle;
	@BindView(R.id.sim_message)
	LinearLayout mSimMessage;

	ImageView mImageView;
	TextView mInviteCodeTv;
	LinearLayout mInviteCodeLl;

	private String mUrl, mInviteCode, mLeftRecommendTimes = "";
	private String mQrFile;
	private Bitmap mIconBitmap, mQrCodeBitmap;

	private RecommendPermissionModel.ShareBean mShareBean;

	private List<View> mViewList;
	private ShareAgent mShareAction;
	private int mPermissionRequestCodeExternalStorage = DEFAULT_PERMISSION_REQUEST_CODE_EXTERNAL_STORAGE;

	public static void start(Activity aty, Intent intent) {
		aty.startActivity(intent);
	}

	@Override
	protected void onDestroy() {
		mShareAction.onDestroy();
		super.onDestroy();
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mQrFile = Environment.getExternalStorageDirectory() + File.separator + "Images" + File.separator;
		CLog.i(TAG, "QR image file directory path: " + mQrFile);
	}

	@Override
	public void pretreatmentAfterSetBaseView() {
		super.pretreatmentAfterSetBaseView();
		Intent intent = getIntent();
		if (intent != null) {
			String content = intent.getStringExtra(LASScanRecommendActivity.CONTENT);
			String title = intent.getStringExtra(LASScanRecommendActivity.TITLE);
			mUrl = intent.getStringExtra(LASScanRecommendActivity.URI);
			mInviteCode = intent.getStringExtra(LASScanRecommendActivity.CODE);
			mLeftRecommendTimes = intent.getStringExtra(LEFT_RECOMMEND_LAS_TIMES);
			mShareBean = new RecommendPermissionModel.ShareBean(content, title, mUrl, mInviteCode);
		}
	}

	@Override
	public int getContentViewRes() {
		return R.layout.las_scan_recommend_activity_layout;
	}

	@Override
	public void initContentView() {
		setBtnRightVisible(false);
		setTitleLeftVisible(false);
		setTitleVisible(true);
		setTitle(R.string.scan_code_recommend);

		mViewList = new ArrayList<>();
		View qrCodePage = View.inflate(this, R.layout.las_recommend_page_one, null);
		View stepsPage = View.inflate(this, R.layout.las_recommend_page_two, null);
		mImageView = (ImageView) qrCodePage.findViewById(R.id.las_qr_code);
		mInviteCodeTv = (TextView) qrCodePage.findViewById(R.id.las_invite_code);
		mInviteCodeLl = (LinearLayout) qrCodePage.findViewById(R.id.las_invite_code_ll);
		TextView leftRecommendTimesTv = (TextView) qrCodePage.findViewById(R.id.recommend_las_left_times_tv);
		View leftRecommendTimesLl = qrCodePage.findViewById(R.id.left_recommend_las_times_ll);
		if (TextUtils.isEmpty(mLeftRecommendTimes)){
			leftRecommendTimesLl.setVisibility(View.GONE);
		}else {
			leftRecommendTimesLl.setVisibility(View.VISIBLE);
			leftRecommendTimesTv.setText(mLeftRecommendTimes);
		}
		ImageView tipsIv = (ImageView) qrCodePage.findViewById(R.id.tips_iv);
		tipsIv.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showTipsDialog(getString(R.string.recommend_las_tips), false);
			}
		});

		mViewList.add(qrCodePage);
		mViewList.add(stepsPage);

		mViewpager.setAdapter(mPagerAdapter);
		mViewpager.addOnPageChangeListener(mOnPageChangeListener);
		mInkPagerIndicator.setViewPager(mViewpager);

		mShareAction = new ShareAgent(this, mShareBean.url, mShareBean.title, mShareBean.content, this);
	}

	@Override
	public void onBackBtnPressed() {
		super.onBackBtnPressed();
		finish();
	}

	private void buildCode(final String source) {
		mIconBitmap = ((BitmapDrawable) ContextCompat.getDrawable(this, R.drawable.ic_launcher_yundai)).getBitmap();
		GlobalVariableConfig.getExecutorService().execute(new Runnable() {
			@Override
			public void run() {
				try {
					float screenWidth = getResources().getDisplayMetrics().widthPixels;
					int baseWidth = 160;
					if (screenWidth > 1080) {
						baseWidth = 190;
					}
					CLog.i(TAG, "screenWidth="+screenWidth);
					int width = DensityUtil.dip2px(LASScanRecommendActivity.this, baseWidth);
					int height = DensityUtil.dip2px(LASScanRecommendActivity.this, baseWidth);

					mQrCodeBitmap = QRCodeUtil.createQRImage(source, width, height, mIconBitmap, getResources().getDisplayMetrics().density);
					if (null != mQrCodeBitmap) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								mImageView.setImageBitmap(mQrCodeBitmap);
								mImageView.setOnLongClickListener(LASScanRecommendActivity.this);
								mInviteCodeLl.setVisibility(View.VISIBLE);
								mInviteCodeTv.setText(mInviteCode);
								mInviteCodeTv.setOnClickListener(new View.OnClickListener() {
									@Override
									public void onClick(View view) {
										if(!TextUtils.isEmpty(mInviteCode)){
											ClipboardManager cmb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
											ClipData clip = ClipData.newPlainText("", mInviteCode);
											cmb.setPrimaryClip(clip);
											showToast("邀请码已复制");
										}
									}
								});
							}
						});
					}
				} catch (Exception e) {
					showToast("二维码生成失败失败！");
				}
			}
		});
	}

	private void saveQrCodeImg() {
		if (FileUtils.saveBitmapToFile(
				Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(),
				FileUtils.LAS_QR_CODE_IMG_FILE_NAME, mQrCodeBitmap)) {
			showToast(R.string.save_qr_code_img_success);
			VibratorUtil.Vibrate(this, 100);
			updateQrCodeToAlbum();
		}
	}

	/**
	 * 将保存图片更新到相册图库
	 */
	private void updateQrCodeToAlbum() {
		File f = new File(Environment.getExternalStoragePublicDirectory(
				Environment.DIRECTORY_DOWNLOADS) + File.separator + FileUtils.LAS_QR_CODE_IMG_FILE_NAME);
		// 通知图库更新
		sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(f)));
	}

	@Override
	public boolean onLongClick(View view) {
		switch (view.getId()) {
			case R.id.las_qr_code:
				if (!hasWriteStoragePermission(mPermissionRequestCodeExternalStorage)) {
					return true;
				}
				saveQrCodeImg();
				break;
		}
		return true;
	}

	@Override
	protected void permissionsAllGrantedSuccess(int requestCode) {
		if (requestCode == mPermissionRequestCodeExternalStorage){
			saveQrCodeImg();
		}
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return null;
	}

	private PagerAdapter mPagerAdapter = new PagerAdapter() {
		@Override
		public int getCount() {
			return mViewList.size();
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			container.addView(mViewList.get(position));
			if (position == 0) {
				buildCode(mUrl);
			}
			return mViewList.get(position);
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}
	};

	private ViewPager.OnPageChangeListener mOnPageChangeListener = new ViewPager.OnPageChangeListener() {
		@Override
		public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
		}

		@Override
		public void onPageSelected(int position) {
		}

		@Override
		public void onPageScrollStateChanged(int state) {
		}
	};

	@Override
	public void sendMsg(String title, String content, String url) {
		Uri uri = Uri.parse("smsto:");
		Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
		intent.putExtra("sms_body", "【友金云贷】推荐您使用友金云贷，仅凭身份证，3分钟线上申请，最高可贷50万！[" + url + "]");
		startActivity(intent);
	}

	private boolean isAvailable(Context ctx, String packageName) {
		final PackageManager pkgMgr = ctx.getPackageManager();
		List<PackageInfo> info = pkgMgr.getInstalledPackages(0);
		for (int i = 0; i < info.size(); i++) {
			if (info.get(i).packageName.equalsIgnoreCase(packageName))
				return true;
		}
		return false;
	}

	@OnClick({R.id.we_chat_friend, R.id.we_chat_circle, R.id.sim_message})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.we_chat_friend:
				if (!isAvailable(this, wxPackage)) {
					showToast(R.string.application_not_installed);
					return;
				}
				if (null != mShareAction) {
					String title = "友金云贷 | 助您资金周转更轻松";
					String content = "仅凭身份证，3分钟线上申请，最高可贷50万";
					mShareAction.setTitle(title);
					mShareAction.setContent(content);
					ShareAgent.getmShareActionListener().resetTitleAndContent(title, content);
					mShareAction.sharePlantForm(ShareAgent.ShareAction.WX_FRIEND, R.drawable.ic_launcher_yundai);
				}
				break;
			case R.id.we_chat_circle:
				if (!isAvailable(this, wxPackage)) {
					showToast(R.string.application_not_installed);
					return;
				}
				if (null != mShareAction) {
					String title = "友金云贷 | 仅凭身份证，3分钟线上申请，最高可贷50万";
					String content = "仅凭身份证，3分钟线上申请，最高可贷50万";
					mShareAction.setTitle(title);
					mShareAction.setContent(content);
					ShareAgent.getmShareActionListener().resetTitleAndContent(title, content);
					mShareAction.sharePlantForm(ShareAgent.ShareAction.WX_CIRCLE, R.drawable.ic_launcher_yundai);
				}
				break;
			case R.id.sim_message:
				if (null != mShareAction) {
					mShareAction.sharePlantForm(ShareAgent.ShareAction.SEND_FRIEND, R.drawable.ic_launcher_yundai);
				}
				break;
				default:
					break;
		}
	}
}
